package com.guoxin.artconcurrency.chapter6;

import java.util.concurrent.*;

/**
 * @author guoxin
 * @date 2019/8/6
 */
public class CountTask extends RecursiveTask<Integer> {
    private static final int THRESHOLD = 2;
    private int start;
    private int end;

    public CountTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    /**
     * The main computation performed by this task.
     *
     * @return the result of the computation
     */
    @Override
    protected Integer compute() {
        int sum = 0;
        boolean canCompute = end - start <= THRESHOLD;
        if (canCompute) {
            for (int i = start; i <= end; i++) {
                sum += i;
            }
        } else {
            int middle = (start + end) / 2;
            CountTask leftTaks = new CountTask(start, middle);
            CountTask rightTask = new CountTask(middle + 1, end);
            leftTaks.fork();
            rightTask.fork();
            sum = leftTaks.join() + rightTask.join();
        }
        return sum;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinPool pool = new ForkJoinPool();
        CountTask task = new CountTask(1, 4);
        ForkJoinTask<Integer> result = pool.submit(task);

        //异常处理
        if (result.isCompletedAbnormally()) {
            Throwable exception = result.getException();
            exception.printStackTrace();
        }
        System.out.println(result.get());
    }
}
